package com.sdau.repairmaster.UIFile;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.sdau.repairmaster.R;
import com.sdau.repairmaster.logic.model.User;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static java.lang.Thread.sleep;


public class RegisterActivity_two extends AppCompatActivity implements View.OnClickListener {
    private EditText etPhoneNumber;//获取手机号
    private String password;
    private EditText etCode;//获取验证码
    private Button btnSendCode;//发送验证码
    private Button btnCheckCode;//检查验证码
    private String phone;//手机号
    private String code;//验证码

    private final int FAILURE_CODE = 1001;//失败
    private final int SUCCESS_CODE = 1000;//成功


    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS_CODE://成功
                    String data = (String) msg.obj;
                    if ("true".equals(data.trim()))
                        updateSuccess();
                    else
                        updateFaile();
                    break;
                case FAILURE_CODE://失败
                    Toast.makeText(RegisterActivity_two.this, "网络异常", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_two);
        initView();
        Intent intent = getIntent();
        password = intent.getStringExtra("password");
        EventHandler handler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

//                result = SMSSDK.RESULT_COMPLETE;
//                event = SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE;

                if (result == SMSSDK.RESULT_COMPLETE) {

                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //更新密码和手机号
                        //郑哲：此处逻辑是不是应该写到验证码验证成功之后，在此重新设置密码，验证码作用失效？
                        User user = new User();
                        user.setPwd(getIntent().getStringExtra("password"));
                        user.setAccount(getIntent().getStringExtra("account"));
                        user.setPhone(etPhoneNumber.getText().toString());
                        updatePwdAndPhone(user);


                        //提交验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity_two.this, "验证成功",
                                        Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(RegisterActivity_two.this, HomeActivity.class));//跳转到主页面
                                //设置手机号，设置新密码密码，到此步才为用户设置密码，防止用户跳过绑定手机环节，
                                // Toast.makeText(RegisterActivity_two.this,password,Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        });
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity_two.this, "验证码已发送", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        Log.i("test", "test");
                    }
                } else {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    throwable.printStackTrace();
                    Log.i("1234", throwable.toString());
                    try {
                        JSONObject obj = new JSONObject(throwable.getMessage());
                        final String des = obj.optString("detail");
                        if (!TextUtils.isEmpty(des)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity_two.this, des, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        SMSSDK.registerEventHandler(handler);


    }

    public void initView() {
        etPhoneNumber = findViewById(R.id.et_register_two_phone);
        etCode = findViewById(R.id.et_register_two_code_input);
        btnSendCode = findViewById(R.id.register_two_sms_call);
        btnCheckCode = findViewById(R.id.bt_register_two_submit);
        etPhoneNumber.setOnClickListener(this);
        etCode.setOnClickListener(this);
        btnSendCode.setOnClickListener(this);
        btnCheckCode.setOnClickListener(this);
        findViewById(R.id.ib_navigation_back).setOnClickListener((View.OnClickListener) this);

//        etPhoneNumber.setText("123456789");
//        etCode.setText("512649");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_two_sms_call:
                phone = etPhoneNumber.getText().toString();
                if (!TextUtils.isEmpty(phone.trim())) {
                    if (phone.trim().length() == 11) {
                        SMSSDK.getVerificationCode("86", phone);
                        etCode.requestFocus();
                    } else {
                        Toast.makeText(RegisterActivity_two.this, "请输入完整电话号码", Toast.LENGTH_SHORT).show();
                        etPhoneNumber.requestFocus();
                    }
                } else {
                    Toast.makeText(RegisterActivity_two.this, "请输入您的电话号码", Toast.LENGTH_SHORT).show();
                    etPhoneNumber.requestFocus();
                }
                break;
            case R.id.bt_register_two_submit:
                code = etCode.getText().toString();
                if (!TextUtils.isEmpty(code.trim())) {
                    if (code.trim().length() == 6) {
                        SMSSDK.submitVerificationCode("86", phone, code);

                    } else {
                        Toast.makeText(RegisterActivity_two.this, "请输入完整验证码",
                                Toast.LENGTH_LONG).show();
                        etCode.requestFocus();
                    }
                } else {
                    Toast.makeText(RegisterActivity_two.this, "请输入验证码",
                            Toast.LENGTH_LONG).show();
                    etCode.requestFocus();
                }


                break;
            case R.id.ib_navigation_back:
                finish();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    /*
    OkHttp上传JSON字符串，更新pwd 和 phone
     */
    public void updatePwdAndPhone(User user) {
        final String URL_login = "http://39.99.174.38/RepairAdmin/userServlet";
        final Message message = Message.obtain();


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.6'
        Gson gson = new Gson();
        //使用Gson将对象转换为json字符串
        String json = gson.toJson(user);


        RequestBody requestBody = new FormBody.Builder()
                .add("json", json)
                .add("flag", "updatePwdAndPhone")
                .build();

        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what = FAILURE_CODE;
                message.obj = e.getMessage();//失败的信息
                handler2.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data = response.body().string();
                message.what = SUCCESS_CODE;
                message.obj = data;
                handler2.sendMessage(message);
            }
        });

    }

    /*
    切换线程更新UI
     */
    private void showResponse(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作，将结果显示到界面上
                Toast.makeText(RegisterActivity_two.this, str, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*
    更新密码成功
     */
    public void updateSuccess() {

    }

    /*
    更新密码失败
     */
    public void updateFaile() {
        startActivity(new Intent(RegisterActivity_two.this, LoginActivity.class));

    }

}
